<template>
  <div class="position-manage">
    <!-- 筛选栏：状态筛选 + 发布按钮 -->
    <div class="filter-bar">
      <el-select
        v-model="statusFilter"
        placeholder="选择状态"
        @change="handleStatusChange"
        clearable
        style="width: 180px"
      >
        <el-option label="全部" value=""></el-option>
        <el-option label="审核中" value="pending"></el-option>
        <el-option label="已发布" value="published"></el-option>
        <el-option label="审核失败" value="faild"></el-option>
      </el-select>

      <el-button type="primary" @click="toPostJob" style="margin-left: 15px">
        <i class="el-icon-plus"></i> 发布新职位
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="filteredTableData"
      border
      stripe
      :loading="loading"
      row-key="id"
      style="margin-top: 15px; width: 100%"
    >
      <!-- 序号列 -->
      <el-table-column
        type="index"
        label="序号"
        width="60"
        align="center"
      ></el-table-column>

      <!-- 职位名称 -->
      <el-table-column
        prop="current.positionName"
        label="职位名称"
        align="center"
        show-overflow-tooltip
      ></el-table-column>

      <!-- 职位类型 -->
      <el-table-column
        prop="current.positionType"
        label="职位类型"
        width="105"
        align="center"
      ></el-table-column>

      <!-- 学历要求 -->
      <el-table-column
        prop="current.education"
        label="学历要求"
        width="100"
        align="center"
        :formatter="formatEducation"
      ></el-table-column>

      <!-- 薪资范围 -->
      <el-table-column label="薪资范围" width="180" align="center">
        <template #default="scope">
          {{ scope.row.current.lowestSalaryMonth }} -
          {{ scope.row.current.highestSalaryMonth }} 元/月
        </template>
      </el-table-column>

      <!-- 发布时间 -->
      <el-table-column
        prop="current.startAt"
        label="发布时间"
        width="110"
        align="center"
        :formatter="formatDate"
      ></el-table-column>

      <!-- 截止日期 -->
      <el-table-column
        prop="current.endAt"
        label="截止日期"
        width="110"
        align="center"
        :formatter="formatDate"
      ></el-table-column>

      <!-- 审核状态 -->
      <el-table-column label="审核状态" width="200" align="center">
        <template #default="scope">
          <PositionStatusTag
            :status="scope.row.status"
            :scene="scope.row.scene"
            :failed-message="scope.row.failedMessage"
          />
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="240" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleView(scope.row.id)"
            >查看</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope.row.id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="handleCurrentChange"
        layout="total, prev, pager, next"
        :disabled="total === 0"
        style="margin-top: 15px"
      />
    </div>
  </div>
</template>

<script>
import PositionStatusTag from "@/views/CompanyViews/company-position/component/PositionStatusTag.vue";

import {
  getUserPublishPositions,
  getUserPositions,
  cancelPublishPosition,
  cancelUpdateUserPosition,
  deletePosition,
} from "@/api/recuriter/position";
import { isFailedStatus, isPendingStatus } from "@/util/positionStatus";

export default {
  components: {
    PositionStatusTag,
  },
  data() {
    return {
      statusFilter: "",
      allTableData: [],
      currentPage: 1,
      pageSize: 10,
      loading: false,
    };
  },
  computed: {
    filteredTableData() {
      let filtered = [...this.allTableData];
      if (this.statusFilter === "pending") {
        filtered = filtered.filter((item) =>
          ["VERIFY_COMPANY_REVIEW", "VERIFY_MANAGER_REVIEW"].includes(
            item.status
          )
        );
      } else if (this.statusFilter === "published") {
        filtered = filtered.filter((item) => item.status === "NORMAL");
      } else if (this.statusFilter === "faild") {
        filtered = filtered.filter((item) =>
          ["VERIFY_COMPANY_FAILED", "VERIFY_MANAGER_FAILED"].includes(
            item.status
          )
        );
      }

      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return filtered.slice(startIndex, endIndex);
    },
    total() {
      if (this.statusFilter === "pending") {
        return this.allTableData.filter((item) =>
          ["VERIFY_COMPANY_REVIEW", "VERIFY_MANAGER_REVIEW"].includes(
            item.status
          )
        ).length;
      } else if (this.statusFilter === "published") {
        return this.allTableData.filter((item) => item.status === "NORMAL")
          .length;
      }
      return this.allTableData.length;
    },
  },
  created() {
    this.loadTableData();
  },
  methods: {
    async loadTableData() {
      this.loading = true;
      try {
        const personalPendingRes = await getUserPublishPositions();
        const personalSuccessRes = await getUserPositions();
        const rawData = [
          ...personalPendingRes.data,
          ...personalSuccessRes.data,
        ];
        this.allTableData = rawData;
        this.currentPage = 1;
      } catch (error) {
        console.error("加载岗位数据失败：", error);
        this.$message.error("加载岗位数据失败，请重试");
      } finally {
        this.loading = false;
      }
    },

    handleStatusChange() {
      this.currentPage = 1;
    },

    handleCurrentChange(page) {
      this.currentPage = page;
      document.querySelector(".el-table").scrollTop = 0;
    },
    toPostJob() {
      this.$router.push({ name: "job-posting" });
    },
    // 格式化日期
    formatDate(row, column, cellValue) {
      if (!cellValue) return "-";
      const date = new Date(cellValue);
      return `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
    },

    // 格式化学历
    formatEducation(row, column, cellValue) {
      const eduMap = {
        COLLEGE: "大专",
        UNDERGRADUATE: "本科",
        MASTER: "硕士",
        DOCTOR: "博士",
        OTHER: "其他",
      };
      return eduMap[cellValue] || cellValue;
    },

    // 查看详情
    handleView(id) {
      const targetItem = this.allTableData.find((item) => item.id === id);
      console.log(666, targetItem.status);
      console.log(777, targetItem.scene);
      this.$router.push({
        name: "position-detail",
        params: { id, status: targetItem.status, scene: targetItem.scene },
        query: { from: "person-position-list" },
      });
    },

    // 编辑职位
    handleEdit(id) {
      const targetItem = this.allTableData.find((item) => item.id === id);
      console.log("当前具体职位详情", targetItem.status);
      this.$router.push({
        name: "edit-posting",
        params: {
          id,
          scene: targetItem.scene,
          mode: targetItem.status,
          isEdit: true,
        },
      });
    },

    // 删除职位
    async handleDelete(id) {
      this.$confirm(`确定要删除该职位吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const targetItem = this.allTableData.find((item) => item.id === id);
            const isPending = isPendingStatus(
              targetItem.status,
              targetItem.scene
            );
            const isPendingFail = isFailedStatus(
              targetItem.status,
              targetItem.scene
            );
            if (
              (isPending && targetItem.scene === "code") ||
              (isPendingFail && targetItem.scene === "code")
            ) {
              const isPendingres = await cancelPublishPosition(id);
              this.$store.commit("recruiter/SET_TOKEN", isPendingres.data.data);
            } else if (
              targetItem.scene === "positionId" &&
              targetItem.status === "NORMAL"
            ) {
              const deleteres = await deletePosition(id);
              this.$store.commit("recruiter/SET_TOKEN", deleteres.data.data);
            } else {
              const isUpdateres = await cancelUpdateUserPosition(id);
              this.$store.commit("recruiter/SET_TOKEN", isUpdateres.data.data);
            }
            this.$message.success("删除成功");
            this.loadTableData();
          } catch (error) {
            this.$message.error(error.response?.data?.msg || "删除失败");
            this.loadTableData();
          }
        })
        .catch(() => {
          console.log("删除失败");
        });
    },
  },
};
</script>

<style scoped>
.position-manage {
  padding: 20px;
}
.filter-bar {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.pagination-container {
  text-align: right;
}

::v-deep .el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

::v-deep .el-table .el-tag {
  margin: 0;
}
</style>